/* Copyright © Worklight Ltd. 2006-2011.  All rights reserved. */

package com.worklight.wlclient.api;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;

/**
 * An object that holds the parameters necessary for WLClient.invokeProcedure. 
 * This class is similar to the javascript WL.Client.invokeProcedure JSON parameter block.
 */
public class WLProcedureInvocationData {
	private Object [] parameters;
	private String adapter;
	private String procedure;
	
	/**
	 * Create new WLProcedureInvocationData object to send with the request.
	 * @param adapter - the adapter name on Worklight's server
	 * @param procedure - the procedure name on Worklight's server
	 */
	public WLProcedureInvocationData(String adapter, String procedure) {
		this.adapter = adapter;
		this.procedure = procedure;
	}
	
	/**
	 * Set the request parameters.
	 * The order of the object in the array will be the order sendting them to the adapter
	 * Object [] parameters - array of object from primitive types (String, Integer, Float, Boolean, Double)
	 */
	public void setParameters (Object [] parameters) {
		this.parameters = parameters;
	}
	
	/**
	 * @return all parameters as a map
	 */
	public Map<String, String> getInvocationDataMap() {
		Map<String,String> invocationData = new HashMap<String, String>();
		  
		JSONArray jsonParams = new JSONArray();
		if (parameters != null){
			for (int i = 0; i < parameters.length; ++i) {    
				try {
					jsonParams.put(i, parameters[i]);
				} catch (JSONException e) {
					throw new RuntimeException(e);
				}
			}
		}
		invocationData.put("adapter", adapter);
		invocationData.put("procedure", procedure);
		invocationData.put("parameters", jsonParams.toString());  
		return invocationData;	
	}
}
